package vn.edu.uit.chemistry;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import vn.edu.uit.chemistry.KhoiTaoThongSo.CreateDSHSAsyncTask;
import vn.edu.uit.chemistry.utilities.Contents;
import vn.edu.uit.chemistry.utilities.QRCodeEncoder;
import vn.edu.uit.chemistry.utilities.WebserviceHelper;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class DangNhap extends Activity{
	
	EditText etHoten;
	EditText etMSGV;
	Button btnDangNhap;

	String hoten = "";
	String msgv = "";

	ProgressBar prKhoiTao;
	public static String ipAddress = "";
	public String pathDSHS = Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/hoa hoc/dshs/dshs.xls";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_dang_nhap);
		
		SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
		hoten = prefs.getString("hoten", "");
		msgv = prefs.getString("msgv", "");

		etHoten = (EditText) findViewById(R.id.etHoTen);
		etHoten.setHint(Html.fromHtml("<i>Họ tên giáo viên</i>"));
		etHoten.setText(hoten);

		etMSGV = (EditText) findViewById(R.id.etMSGV);
		etMSGV.setHint(Html.fromHtml("<i>Mã số giáo viên</i>"));
		etMSGV.setText(msgv);

		btnDangNhap = (Button) findViewById(R.id.btnLogin);
		btnDangNhap.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hoten = etHoten.getText().toString().trim();
				msgv = etMSGV.getText().toString().trim();

				SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("hoten", hoten);
				editor.putString("msgv", msgv);
				editor.commit();
				new ScanIPAsyncTask(prKhoiTao).execute();
			}
		});
		
		prKhoiTao = (ProgressBar) findViewById(R.id.progKhoiTao);
	}
	
	public void switchView() {
		Intent intent = new Intent(getApplicationContext(),
				MainActivity.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	final class ScanIPAsyncTask extends AsyncTask<Void, Void, Void> {

		private Boolean isSuccess = false;
		private ProgressBar pR;

		public ScanIPAsyncTask(ProgressBar progress) {
			pR = progress;
			pR.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPreExecute() {
			pR.setVisibility(View.VISIBLE);

		}

		@Override
		protected Void doInBackground(final Void... params) {
			/* Load timezone. this is very slow - may take up to 3 seconds. */
			if (WebserviceHelper.getInstance() != null) {
				WebserviceHelper.destroyInstance();
			}
			isSuccess = WebserviceHelper.isNetAvailable(DangNhap.this);
			if (isSuccess) {
				
				ipAddress = WebserviceHelper.getIPAddress();
				SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("ip", ipAddress.trim());
				editor.putString("port", "54321");
				editor.commit();

				try {
					createQRCode(ipAddress.trim(), "54321");					
				} catch (WriterException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} 
			
			return null;
			
		}

		@Override
		protected void onPostExecute(final Void unused) {
			pR.setVisibility(View.INVISIBLE);
			if (isSuccess) {	
				// 1.Khoi tao socketServer
				
				// 2.Load danh sach hoc sinh
				new CreateDSHSAsyncTask(prKhoiTao).execute();
			} else {
				showDialog(0);
			}
		}
	}

	public void createQRCode(String ip, String port) throws WriterException,
			IOException {

		String input = "0#"+hoten+"#"+msgv+"#"+ ip + "#" + port;
		int smallerDimension = 300;

		QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(input.trim(), null,
				Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(),
				smallerDimension);
		Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();

		String filename = "/hoa hoc/qrcode.png";
		File sd = Environment.getExternalStorageDirectory();
		File dest = new File(sd, filename);

		FileOutputStream out = new FileOutputStream(dest);
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
		out.flush();
		out.close();
	}

	public Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Lỗi xảy ra").setMessage("Không có kết nối mạng!")
				.setPositiveButton("Thoát", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		return builder.create();
	}
	
	final class CreateDSHSAsyncTask extends AsyncTask<Void, Void, Void> {

		private ProgressBar pR;
		private String key = "";
		private String value = "";

		public CreateDSHSAsyncTask(ProgressBar progress) {
			pR = progress;
			pR.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPreExecute() {
			pR.setVisibility(View.VISIBLE);

		}

		@Override
		protected Void doInBackground(Void... params) {
			File inputWorkbook = new File(pathDSHS);
			Workbook w;
			try {
				w = Workbook.getWorkbook(inputWorkbook);
				Sheet sheet = w.getSheet(0);

				/**
				 * DSHS co cau truc sau
				 * key = mshs
				 * neu la lan khoi ta dau tien thi no se co value = tenHS#1
				 * 1 tuc la vang mat
				 * 
				 * Khi hocsinh ket noi thi value = tenHS#IP cua hoc sinh 
				 */
				
				for (int i = 0; i < sheet.getRows(); i++) {
					SharedPreferences ref = getSharedPreferences("DSHS", 0);
					SharedPreferences.Editor editor = ref.edit();
					key = "";
					value = "";
					for (int j = 0; j < sheet.getColumns(); j++) {
						Cell cell = sheet.getCell(j, i);
						CellType type = cell.getType();
						if (type == CellType.LABEL) {
							if (key.equals("")) {
								key = cell.getContents().toString().trim();
							} else {
								value = cell.getContents().toString().trim() + "#1";
							}
						}

					}
					editor.putString(key, value);
					editor.commit();
				}
				
			} catch (BiffException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(final Void unused) {
			pR.setVisibility(View.INVISIBLE);
//			SharedPreferences prefs = getSharedPreferences("DSHS", 0);
//			Map<String,?> keys = prefs.getAll();
//
//			for(Map.Entry<String,?> entry : keys.entrySet()){
//			            Log.d("map values",entry.getKey() + ": " + 
//			                                   entry.getValue().toString());   
//			            
//			 }
			
			switchView();
		}
	}
}
